﻿using Microsoft.Extensions.Logging;
using System.Net;
using System.Text; 

namespace Agile.Infra.Pay
{
    public abstract class AbstractPayService
    {
        public readonly ILogger _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        public AbstractPayService(IHttpClientFactory httpClientFactory, ILogger logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }


        protected async Task<string> HttpRequestAsync(string shipperHawbcodes, HttpRequestMessage httpRequestMessage)
        {
            var apiLog = new StringBuilder();
            var statusCode = HttpStatusCode.OK;
            var result = string.Empty;
            try
            {
                apiLog.AppendLine("请求时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                apiLog.AppendLine("请求地址：" + httpRequestMessage.RequestUri?.AbsoluteUri);
                apiLog.AppendLine("请求方式：" + httpRequestMessage.Method.ToString());
                apiLog.AppendLine("Content-Type：" + httpRequestMessage.Content?.Headers?.ContentType?.ToString());

                if (httpRequestMessage.Content != null && httpRequestMessage.Content.Headers != null)
                {
                    foreach (var header in httpRequestMessage.Content.Headers)
                    {
                        if (header.Value != null || header.Value.Count() < 1) continue;
                        if (string.Equals(header.Key, "Content-Type", StringComparison.OrdinalIgnoreCase)) continue;

                        apiLog.AppendLine(string.Format($"{header.Key}：{string.Join(",", header.Value)}"));
                    }
                }
                if (httpRequestMessage.Method == HttpMethod.Post && httpRequestMessage.Content != null)
                {
                    apiLog.AppendLine("请求数据：" + await httpRequestMessage.Content.ReadAsStringAsync());
                }

                apiLog.AppendLine();
                apiLog.AppendLine();
                apiLog.AppendLine();

                var httpClient = _httpClientFactory.CreateClient(this.GetType().Name);
                httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
                httpClient.Timeout = new TimeSpan(0, 0, 20);
                httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0");
                var response = await httpClient.SendAsync(httpRequestMessage);
                statusCode = response.StatusCode;
                result = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"支付异常：{ex.Message}");
                throw new PayException("调用支付接口出现异常，请稍候再试");
            }
            finally
            {
                try
                {
                    apiLog.AppendLine("响应状态：" + (int)statusCode);
                    apiLog.AppendLine("返回时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    apiLog.Append("返回结果：\r\n" + result);
                }
                catch { }
            }
            if (statusCode != System.Net.HttpStatusCode.OK)
            {
                throw new PayException($"支付失败，返回结果【{result}】");
            }
            return result;
        }

    }
}
